package com.wyh.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<ConfigClass> implements Ordered {

    //让Spring Cloud Gateway能够识别该过滤器的配置类，以此在解析配置时可以把参数绑定到配置类中。
    public CustomGatewayFilterFactory() {
        super(ConfigClass.class);
    }

    //编写自定义的过滤逻辑
    @Override
    public GatewayFilter apply(ConfigClass config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                System.out.println("[Pre] Request Filter, name:" + config.getName());
                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    System.out.println("[Post] Response Filter");
                }));
            }
        };
    }

    //指定过滤器的执行顺序
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
